//
//  BAAlbumDetailCellNode.m
//  BabyAlbum
//
//  Created by master on 17/2/15.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BANormalDetailViewNode.h"
#import "BAAlbumListLayout.h"
#import "BAResourceNode.h"
#import "BANormalHeaderNode.h"
#import "SuPhotoPicker.h"
#import "TZImagePickerController.h"
#import "MWPhotoBrowser.h"
#import "BAVideoHeaderNode.h"

@interface BANormalDetailViewNode () <ASCollectionDataSource, ASCollectionDelegateFlowLayout, BACollectionViewLayoutDelegate,ASCollectionViewLayoutInspecting,TZImagePickerControllerDelegate,UIActionSheetDelegate,MWPhotoBrowserDelegate>



@property (nonatomic, strong) NSMutableArray<BAAlbumItem *> *resourceList;

@property (nonatomic, strong) NSMutableArray <MWPhoto *> *photos;


@property (nonatomic, strong) ASButtonNode *returnButton;
@property (nonatomic, strong) ASButtonNode *editButton;
@property (nonatomic, strong) ASEditableTextNode *titleNode;


@property (nonatomic, strong) ASCellNode *headerNode;

@property (nonatomic, strong) UIView *backgroundView;

//@property (nonatomic, strong) UILongPressGestureRecognizer *longPress;

@end

@implementation BANormalDetailViewNode


- (instancetype)initWithData:(BAAlbumModel *)model{
    if(self = [super init]) {

        self.albumModel = model;

        [self viewInit];

    }
    return self;
}


- (void)viewInit {
    BAAlbumListLayout *layout = [[BAAlbumListLayout alloc] init];
    layout.numberOfColumns = 3;
    layout.columnSpacing = 0;
    //    [self reloadData];
    self.backgroundColor = [UIColor clearColor];
    layout.headerHeight = [self.albumModel.cover.type == BAResourceTypeVideo ? [BAVideoHeaderNode class] : [BANormalHeaderNode class] calculteHeightWithData:self.albumModel];
    
    self.collectionNode = [[ASCollectionNode alloc] initWithCollectionViewLayout:layout];
    self.collectionNode.dataSource = self;
    self.collectionNode.delegate = self;
    self.collectionNode.view.layoutInspector = self;
    self.collectionNode.view.contentInset = UIEdgeInsetsMake(10, 0, 10, 0);
    
    self.collectionNode.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.collectionNode.backgroundColor = [UIColor clearColor];
//    self.collectionNode.cornerRadius = 10;
    [self.collectionNode registerSupplementaryNodeOfKind:UICollectionElementKindSectionHeader];
    [self addSubnode:self.collectionNode];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.collectionNode.view.showsHorizontalScrollIndicator = NO;
        self.collectionNode.view.showsVerticalScrollIndicator = NO;
    });
    
    self.backgroundView = [[UIView alloc] init];
    self.backgroundView.backgroundColor = [UIColor whiteColor];
    self.backgroundView.clipsToBounds = YES;
    self.backgroundView.cornerRadius = 10;
    self.backgroundView.alpha = 1;
    [self.collectionNode.view insertSubview:self.backgroundView atIndex:0];
    
    // 添加contentSize Observer
    [self.collectionNode.view addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
}

//移除Observer
- (void)dealloc {
    [self.collectionNode.view removeObserver:self forKeyPath:@"contentSize"];
}


// 每次变更contentSize 变更背景大小
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if(object == self.collectionNode.view) {
        self.backgroundView.frame = CGRectMake(0, 0, self.collectionNode.frame.size.width, self.collectionNode.view.contentSize.height);
        NSLog(@"%@",self.collectionNode.view.subviews);

        for (UIView *subView in self.collectionNode.view.subviews) {
            if(subView != self.backgroundView) {
                [self.collectionNode.view bringSubviewToFront:subView];
            }
        }
    }
}

- (void)didLoad {
    [super didLoad];
    self.resourceList = [NSMutableArray arrayWithArray:[self.albumModel fetchResourceList]];
}


- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{
//    self.collectionNode.style.preferredSize = CGSizeMake(constrainedSize.max.width, kScreenHeight - 164);
//
//    
//    CGFloat hor_interval = (kScreenWidth - (40*2) - (10 *2) - _titleNode.style.preferredSize.width) / 2;


    return [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(0, 10, 60, 10) child:self.collectionNode];
}

//// 存在闪屏
//- (void)setIsEditing:(BOOL)isEditing {
//    if(_isEditing != isEditing) {
//        _isEditing = isEditing;
//        if(_isEditing) {
//            //            [[XYKeyboardHelper sharedInstance] enableKeyboardHelper];
//            //            [self setUpForDismissKeyboard];
//            self.titleNode.textView.userInteractionEnabled = YES;
//            self.editButton.hidden = NO;
//            [self.view removeGestureRecognizer:self.longPress];
//        }else {
//            [self.view endEditing:YES];
//            self.titleNode.textView.userInteractionEnabled = NO;
//            self.editButton.hidden = YES;
//            [self.view addGestureRecognizer:self.longPress];
//        }
//        [self reloadData];
//    }
//}




- (void)reloadData {
    [self.collectionNode reloadData];
}

- (void)back {
    [self.manager.navigationController popViewControllerAnimated:YES];
}


- (void)deleteAlbum {
    [BADB deleteAlbum:self.albumModel];
    [BAALBUM_DATA reloadData];
    [self back];
}
//TODO: 2.22 写视频的存储及读取测试
- (void)save {
    if(![self.albumModel.cover isSetted]) {
        [MBProgressHUD showError:@"没有封面"];
        return;
    }
    if(![self.albumModel.title length]) {
        [MBProgressHUD showError:@"没有标题"];
        return;
    }
    
    //    self.albumModel.desc = self.de
    
    [BADB updateAlbumDataWithModel:self.albumModel];
    [self back];
    [BAALBUM_DATA reloadData];
}

#pragma mark - ASCollectionView Data Source

- (ASCellNodeBlock)collectionNode:(ASCollectionNode *)collectionNode nodeBlockForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    BAAlbumItem *item = self.resourceList[indexPath.row];
    return ^{
        BAResourceNode *imageNode;
        if(item.type == BAResourceTypeImage) {
            BAAlbumImageItem *imageItem = (BAAlbumImageItem *)item;
            imageNode = [[BAResourceNode alloc] initWithImage:imageItem.image editMode:NO];
        } else {
            BAAlbumVideoItem *videoItem = (BAAlbumVideoItem *)item;
            imageNode = [[BAResourceNode alloc] initWithAsset:videoItem.video editMode:NO];
        }
        return imageNode;
    };
}


- (NSInteger)collectionNode:(ASCollectionNode *)collectionNode numberOfItemsInSection:(NSInteger)section
{
    return self.resourceList.count;
}

- (NSInteger)numberOfSectionsInCollectionNode:(ASCollectionNode *)collectionNode
{
    return 1;
}


- (ASSizeRange)collectionView:(ASCollectionView *)collectionView constrainedSizeForNodeAtIndexPath:(NSIndexPath *)indexPath
{
    BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
    return ASSizeRangeMake(CGSizeZero, [layout itemSizeAtIndexPath:indexPath]);
}



- (ASSizeRange)collectionView:(ASCollectionView *)collectionView constrainedSizeForSupplementaryNodeOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
    return ASSizeRangeMake(CGSizeZero, [layout headerSizeForSection:indexPath.section]);
}

- (ASScrollDirection)scrollableDirections
{
    return ASScrollDirectionVerticalDirections;
}

/**
 * Asks the inspector for the number of supplementary views for the given kind in the specified section.
 */
- (NSUInteger)collectionView:(ASCollectionView *)collectionView supplementaryNodesOfKind:(NSString *)kind inSection:(NSUInteger)section
{
    return [kind isEqualToString:UICollectionElementKindSectionHeader] ? 10 : 0;
}

- (ASCellNode *)collectionNode:(ASCollectionNode *)collectionNode nodeForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0) {
        
        self.headerNode = [[self.albumModel.cover.type == BAResourceTypeVideo ? [BAVideoHeaderNode class] : [BANormalHeaderNode class]  alloc] initWithData:self.albumModel];
        __weak typeof(self) weakSelf = self;

        if([self.headerNode isKindOfClass:[BANormalHeaderNode class]]) {
            BANormalHeaderNode *node = (BANormalHeaderNode *)self.headerNode;
            [node setTapBlock:^{
                [weakSelf showPhotoBrowerWithIndex:-1];
            }];
        }
        return self.headerNode;
        
    }
    return [[ASCellNode alloc] init];
}


- (CGSize)collectionView:(ASCollectionNode *)collectionNode layout:(UICollectionViewLayout *)collectionViewLayout originalItemSizeAtIndexPath:(NSIndexPath *)indexPath
{
    ASCellNode *cellNode = [collectionNode nodeForItemAtIndexPath:indexPath];
    if ([cellNode isKindOfClass:[BAResourceNode class]]) {
        CGSize size =  [(BAResourceNode *)cellNode calculatedSize];
        return size;
    }
    return CGSizeMake(120, 120);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (void)collectionNode:(ASCollectionNode *)collectionNode didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    [self showPhotoBrowerWithIndex:indexPath.row];
}


- (void)editableTextNodeDidUpdateText:(ASEditableTextNode *)editableTextNode {
    self.albumModel.title = editableTextNode.textView.text;
}


#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (void)showPhotoBrowerWithIndex:(NSInteger)index {
    // Create array of MWPhoto objects
    self.photos = [NSMutableArray array];
    
    // 封面加入
    if(self.albumModel.cover) {
        index ++;
        if(self.albumModel.cover.type == BAResourceTypeImage) {
            BAAlbumImageItem *imageItem = (BAAlbumImageItem *)self.albumModel.cover;
            [self.photos addObject:[MWPhoto photoWithImage:imageItem.image]];
        } else if(self.albumModel.cover.type == BAResourceTypeVideo) {
            BAAlbumVideoItem *videoItem = (BAAlbumVideoItem *)self.albumModel.cover;
            
            [self.photos addObject:[MWPhoto videoWithURL:videoItem.video.URL]];
        }
    }
    
    for(BAAlbumItem *item in self.resourceList) {
        if(item.type == BAResourceTypeImage) {
            BAAlbumImageItem *imageItem = (BAAlbumImageItem *)item;
            [self.photos addObject:[MWPhoto photoWithImage:imageItem.image]];
        } else if(item.type == BAResourceTypeVideo) {
            BAAlbumVideoItem *videoItem = (BAAlbumVideoItem *)item;
            
            [self.photos addObject:[MWPhoto videoWithURL:videoItem.video.URL]];
        }
    }
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    
    // Set options
    browser.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    browser.autoPlayOnAppear = NO; // Auto-play first video
    
    // Customise selection images to change colours if required
    browser.customImageSelectedIconName = @"ImageSelected.png";
    browser.customImageSelectedSmallIconName = @"ImageSelectedSmall.png";
    
    // Optionally set the current visible photo before displaying
    [browser setCurrentPhotoIndex:index];
    
    // Present
    [self.manager.navigationController pushViewController:browser animated:YES];
    
    // Manipulate
    [browser showNextPhotoAnimated:YES];
    [browser showPreviousPhotoAnimated:YES];
    //    [browser setCurrentPhotoIndex:10];
}


- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}

- (void)getVideoFromPHAsset:(PHAsset *)asset data:(void (^)(AVURLAsset *asset))block {
    PHVideoRequestOptions *option = [PHVideoRequestOptions new];
    
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:option resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        dispatch_async(dispatch_get_main_queue(), ^{
            AVURLAsset * ass= (AVURLAsset *)asset;
            //            NSData *data = [NSData dataWithContentsOfURL:ass.URL];
            block(ass);
        });
    }];
}
@end
